package com.wnhz.work.yz.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.bean.PersonBean;
import com.wnhz.work.yz.utils.AlbumImagePath;
import com.wnhz.work.yz.utils.BitnapUtils;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;
import com.wnhz.work.yz.view.CircularImage;
import com.wnhz.work.yz.view.SkillBookPop;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class AddGroupActivity extends BaseActivity implements View.OnClickListener {
    private SwipeMenuListView group_person_list, manager_list;
    private EditText group_title;
    private LinearLayout ll_group_logo;
    private CircularImage group_logo, bg;
    private LinearLayout add_manager, add_person;

    /**
     * String targetPath = imagePath;
     * //调用压缩图片的方法，返回压缩后的图片path
     * String compressImage = BitnapUtils.compressImage(targetPath, targetPath, 30);
     * File compressedPic = new File(compressImage);
     * map.put("headimg", compressedPic);
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_group);
        initTitle();
        initView();
        initData();
    }

    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("创建团队");
        //title.setTextSize(20);
        title.setTextColor(getResources().getColor(R.color.main_color));
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setText("完成");
        submit.setTextColor(getResources().getColor(R.color.main_color));
        submit.setOnClickListener(this);
        submit.setVisibility(View.VISIBLE);
    }


    private void initView() {
        bg = (CircularImage) findViewById(R.id.bg);
        group_title = (EditText) findViewById(R.id.group_title);
        ll_group_logo = (LinearLayout) findViewById(R.id.ll_group_logo);
        ll_group_logo.setOnClickListener(this);
        group_logo = (CircularImage) findViewById(R.id.group_logo);
        add_manager = (LinearLayout) findViewById(R.id.add_manager);
        add_manager.setOnClickListener(this);
        add_person = (LinearLayout) findViewById(R.id.add_person);
        add_person.setOnClickListener(this);

        manager_list = (SwipeMenuListView) findViewById(R.id.manager_list);
        group_person_list = (SwipeMenuListView) findViewById(R.id.group_person_list);
    }

    private PersonAdapter mAdapter, mAdapter2;

    private void initData() {

        mAdapter = new PersonAdapter(managersId);
        manager_list.setAdapter(mAdapter);

        SwipeMenuCreator creater = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {


                //同理create删除item
                SwipeMenuItem deleteItem = new SwipeMenuItem(AddGroupActivity.this);
                // set item background
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                // set item width
                deleteItem.setWidth(dp2px(90));
                // set item title
                deleteItem.setTitle("删除");
                // set item title fontsize
                deleteItem.setTitleSize(18);
                // set item title font color
                deleteItem.setTitleColor(Color.WHITE);
                // set a icon
                // deleteItem.setIcon(R.mipmap.ic_delete);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };

        manager_list.setMenuCreator(creater);
        manager_list.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                switch (index) {

                    case 0:
                        //删除的逻辑
                        showDialogv7("确定删除该管理员吗？", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                managersId.remove(position);
                                mAdapter.notifyDataSetChanged();
                            }
                        });
                        break;

                    default:
                        break;
                }
                return false;
            }
        });

        mAdapter2 = new PersonAdapter(generalsId);
        group_person_list.setAdapter(mAdapter2);
        group_person_list.setMenuCreator(creater);
        group_person_list.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                switch (index) {

                    case 0:
                        //删除的逻辑
                        showDialogv7("确定删除该组员吗？", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                generalsId.remove(position);
                                mAdapter2.notifyDataSetChanged();
                            }
                        });
                        break;

                    default:
                        break;
                }
                return false;
            }
        });


        mAdapter.notifyDataSetChanged();

    }

    class PersonAdapter extends BaseAdapter {
        List<PersonBean.InfoEntity> data;

        public PersonAdapter(List<PersonBean.InfoEntity> data) {
            this.data = data;

        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                holder = new Holder();
                convertView = View.inflate(AddGroupActivity.this, R.layout.person_info, null);
                holder.head_img = (CircularImage) convertView.findViewById(R.id.head_img);
                holder.head_name = (TextView) convertView.findViewById(R.id.head_name);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            holder.head_name.setText(data.get(position).getUser_name());
            x.image().bind(holder.head_img, data.get(position).getUser_img());
            return convertView;
        }

        class Holder {
            private CircularImage head_img;
            private TextView head_name;
        }
    }


    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:
                if (group_title.getText().toString().equals("")) {
                    MyToast("请填写团队名称");
                    return;
                }
                if (imagePath.equals("")) {
                    MyToast("请选择团队logo");
                    return;
                }
                creatGroup();
                break;
            case R.id.ll_group_logo:
                showPopmenu(v);
                break;
            case R.id.add_manager:
                startActivityForResult(new Intent(this, GroupInviteActivity.class), ADDMANAGER);
                break;
            case R.id.add_person:
                startActivityForResult(new Intent(this, GroupInviteActivity.class), ADDGENERAL);
                break;
        }
    }

    private static final int ADDMANAGER = 333;
    private static final int ADDGENERAL = 444;
    private List<PersonBean.InfoEntity> managersId = new ArrayList<>();
    private List<PersonBean.InfoEntity> generalsId = new ArrayList<>();

    private void creatGroup() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        // 创建团队  参数token、name、logo_img、manage_user_id(管理员id字符串)、general_user_id(成员id字符串)
        map.put("name", group_title.getText().toString());
        String targetPath = imagePath;
        //调用压缩图片的方法，返回压缩后的图片path
        String compressImage = BitnapUtils.compressImage(targetPath, targetPath, 30);
        File compressedPic = new File(compressImage);
        map.put("teamLogo", compressedPic);
        StringBuffer managerStr = new StringBuffer("-");
        for (int i = 0; i < managersId.size(); i++) {
            managerStr.append("" + managersId.get(i).getUser_id() + "-");
        }
        map.put("manage_user_id", managerStr);
        StringBuffer personStr = new StringBuffer("-");
        for (int i = 0; i < generalsId.size(); i++) {
            personStr.append("" + generalsId.get(i).getUser_id() + "-");
        }
        map.put("general_user_id", personStr);

        showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, ":" + value + "\n");
            }
        }
        XUtil.Post(Url.TEAM_CREATETEAM, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("-1".equals(res)) {
                        info = "请重新登录";
                        MyToast(info);
                    } else if ("1".equals(res)) {
                        MyToast(info);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });
    }


    /**
     * ------头像点击
     */
    private WindowManager.LayoutParams lp;
    private SkillBookPop menuWindow;
    private final int FROM_CAMERA_CODE = 111;// 调用相机更改背景图片的请求code
    private final int FROM_ALBUM_CODE = 112;// 调用相册更改背景图片的请求code

    private String imageName;// 原图名称
    private String imagePath;// 原图路径
    private File tempFile;

    /**
     * 图片上传的弹出popwindow
     *
     * @param view
     */
    public void showPopmenu(View view) {
        menuWindow = new SkillBookPop(this, menuItemsOnClick);
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });

        // 显示窗口位置
        menuWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        // 设置layout在PopupWindow中显示的位置
        lp = getWindow().getAttributes();
        lp.alpha = 0.6f;
        getWindow().setAttributes(lp);

    }


    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 弹出pop的菜单点击事件
     */
    private View.OnClickListener menuItemsOnClick = new View.OnClickListener() {
        Intent intent = null;

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.from_camera2:

                    System.out.println("=====1234=====");
                    intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    // 判断存储卡是否可以用，可用进行存储
                    if (hasSdcard()) {
                        String time = System.currentTimeMillis() + "";
                        imageName = time + ".jpg";
                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName)));
                    }
                    System.out.println("拍照的路径---" + imageName);
                    startActivityForResult(intent, FROM_CAMERA_CODE);

                    break;
                case R.id.from_album2:

                    Intent intent = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, FROM_ALBUM_CODE);

                    break;

                default:
                    break;
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            //相册
            case FROM_ALBUM_CODE:
                if (null != data) {
                    // 得到图片的全路径
                    Uri uri = data.getData();

                    String imagePath = AlbumImagePath.getPath(this, uri);
                    updateImage(imagePath, uri);

                }
                break;
            //拍照
            case FROM_CAMERA_CODE:
                boolean hasSdcard = hasSdcard();
                if (hasSdcard) {

                    tempFile = new File(Environment.getExternalStorageDirectory() + "/youZhu/", imageName);
                    Uri uri = Uri.fromFile(tempFile);

                    String imagePath = tempFile.getAbsolutePath();
                    System.out.println("拍照的路径=====：" + imagePath);

                    File file = new File(imagePath);

                    if (!file.exists()) {
                        return;
                    }

                    updateImage(imagePath, uri);

                } else {
                    MyToast("未找到存储卡，无法存储照片！");
                }
                break;
            case ADDGENERAL:
                if (resultCode == RESULT_OK) {
                    generalsId.add((PersonBean.InfoEntity) data.getSerializableExtra("bean"));
                    mAdapter2.notifyDataSetChanged();
                }
                break;
            case ADDMANAGER:
                if (resultCode == RESULT_OK) {
                    managersId.add((PersonBean.InfoEntity) data.getSerializableExtra("bean"));
                    mAdapter.notifyDataSetChanged();
                }
                break;
            default:
                break;
        }

    }

    private void updateImage(String imagePath, Uri uri) {
        if (null == imagePath) {
            return;
        }

        System.out.println("===修改的imagePath===" + imagePath);
        x.image().bind(group_logo, "file://" + imagePath);
        bg.setVisibility(View.VISIBLE);
        this.imagePath = imagePath;
    }

}
